//
//  MyRefreshContrl.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/4.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import FFAutoLayout

class MyRefreshContrl: UIRefreshControl {
    
    //懒加载控件
    lazy var refreshView = MyRefreshView.myRefreshView()
    
    override init() {
        super.init()
        
        //添加
        addSubview(refreshView)
        
        //布局
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        
        //KVO 监听 "自己"
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
    }
    
    //如果不注销 消息，释放对象的时候 程序会崩掉
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    
    
    // 显示提示图标标记
    private var showDownFlag = false
    // 正在加载标记
    private var loadingFlag = false
    
    //KVO 的监听方法
    //往下拉表格， y值会越来越小，y值为负数，控件就会显示
    //拉到一定程度，就会自动刷新
    //如果往上推表格，刷新控件仍然存在，y值会一直变大
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
       // print("拖动刷新控件 ＝＝＝＝＝》 \(frame)")
        if frame.origin.y > 0 {
            return
        }
        
       // 如果正在加载数据，就显示加载动画
        if refreshing && !loadingFlag{
            
            refreshView.startLoadingIconAnim()
            
            loadingFlag = true
            
            return
        }
        
        if frame.origin.y < -50 && !showDownFlag{
           
            showDownFlag = true
            refreshView.rotateDownIcon(showDownFlag)
            
        } else if frame.origin.y > -50 && showDownFlag{
            
            showDownFlag = false
            refreshView.rotateDownIcon(showDownFlag)
        
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoadingIconAnim()
        loadingFlag = false
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  
}
